<template>
	<div id="space-manage-view">
		<!-- 标题栏 -->
		<a-flex justify="space-between" align="center" style="margin-bottom: 16px">
			<h2>空间管理</h2>
			<a-space>
				<a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
				<a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">分析公共图库</a-button>
				<a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">分析全部空间</a-button>
			</a-space>
		</a-flex>
		<!-- 搜索表单 -->
		<a-form layout="inline" :model="searchParams" @finish="doSearch">
			<a-form-item label="空间名称">
				<a-input v-model:value="searchParams.spaceName" placeholder="请输入空间名称" allow-clear />
			</a-form-item>
			<a-form-item label="请输入空间级别">
				<a-select
					v-model:value="searchParams.spaceLevel"
					style="min-width: 150px"
					placeholder="请输入空间级别"
					:options="SPACE_LEVEL_OPTIONS"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="请输入空间类型">
				<a-select
					v-model:value="searchParams.spaceType"
					style="min-width: 150px"
					placeholder="请输入空间类型"
					:options="SPACE_TYPE_OPTIONS"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="用户id">
				<a-input v-model:value="searchParams.userId" placeholder="请输入用户id" allow-clear />
			</a-form-item>
			<a-form-item>
				<a-space>
					<a-button type="primary" html-type="submit">搜索</a-button>
					<a-button type="default" @click="resetSearch">重置</a-button>
				</a-space>
			</a-form-item>
		</a-form>

		<div style="margin-bottom: 16px"></div>

		<!-- 表格 -->
		<a-table
			:columns="columns"
			:data-source="dataList"
			:pagination="pagination"
			@change="doTableChange"
			:loading="loading"
			:scroll="{ x: 'max-content' }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'spaceLevel'">
					<div>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</div>
				</template>
				<template v-if="column.dataIndex === 'spaceType'">
					<div>{{ SPACE_TYPE_MAP[record.spaceType] }}</div>
				</template>
				<template v-if="column.dataIndex === 'spaceUseInfo'">
					<div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
					<div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
				</template>
				<template v-if="column.dataIndex === 'createTime'">
					{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
				</template>
				<template v-if="column.dataIndex === 'editTime'">
					{{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
				</template>
				<template v-else-if="column.key === 'action'">
					<a-space>
						<a-button type="link" :href="`/space_analyze?spaceId=${record.id}`" target="_blank">分析</a-button>
						<a-button type="link" :href="`/add_space?id=${record.id}`" target="_blank">编辑</a-button>
						<a-button danger @click="doDelete(record.id)">删除</a-button>
					</a-space>
				</template>
			</template>
		</a-table>

		<!-- 新增/编辑空间弹窗 -->
		<a-modal
			v-model:open="modalVisible"
			:title="isEdit ? '编辑空间' : '新增空间'"
			:confirmLoading="modalLoading"
			width="600px"
		>
			<a-form ref="formRef" :model="spaceForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-form-item
					label="空间账号"
					name="spaceAccount"
					:rules="[
						{ required: true, message: '请输入空间账号!' },
						{ min: 4, message: '账号长度不能少于4位!' },
					]"
				>
					<a-input v-model:value="spaceForm.spaceAccount" placeholder="请输入空间账号" :disabled="isEdit" />
				</a-form-item>

				<a-form-item label="空间名" name="spaceName" :rules="[{ required: true, message: '请输入空间名!' }]">
					<a-input v-model:value="spaceForm.spaceName" placeholder="请输入空间名" />
				</a-form-item>
				<a-form-item label="空间头像" name="spaceAvatar">
					<a-input v-model:value="spaceForm.spaceAvatar" placeholder="请输入头像URL" />
				</a-form-item>

				<a-form-item label="空间简介" name="spaceProfile">
					<a-textarea
						v-model:value="spaceForm.spaceProfile"
						placeholder="请输入空间简介"
						:rows="3"
						:max-length="200"
						show-count
					/>
				</a-form-item>

				<a-form-item label="空间角色" name="spaceRole" :rules="[{ required: true, message: '请选择空间角色!' }]">
					<a-select v-model:value="spaceForm.spaceRole" placeholder="请选择空间角色">
						<a-select-option value="space">普通空间</a-select-option>
						<a-select-option value="admin">管理员</a-select-option>
					</a-select>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { deleteSpaceUsingPost, listSpaceByPageUsingPost } from '@/api/spaceController'
import { message, Modal } from 'ant-design-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
import dayjs from 'dayjs'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS, SPACE_TYPE_MAP, SPACE_TYPE_OPTIONS } from '@/constants/space'
import { formatSize } from '@/utils'

// 表格加载状态
const loading = ref(false)

// 弹窗相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 空间表单数据
const spaceForm = reactive<{
	id?: number
	spaceAccount?: string
	spaceName?: string
	spaceAvatar?: string
	spaceProfile?: string
	spaceRole?: string
}>({})

// 表单列
const columns = [
	{ title: 'id', dataIndex: 'id', width: 80, align: 'left' },
	{ title: '空间名称', dataIndex: 'spaceName', align: 'left' },
	{ title: '空间级别', dataIndex: 'spaceLevel', align: 'left' },
	{ title: '空间类别', dataIndex: 'spaceType', align: 'left' },
	{ title: '使用情况', dataIndex: 'spaceUseInfo', align: 'left' },
	{ title: '用户 id', dataIndex: 'userId', width: 80, align: 'left' },
	{ title: '创建时间', dataIndex: 'createTime', align: 'left' },
	{ title: '编辑时间', dataIndex: 'editTime', align: 'left' },
	{ title: '操作', key: 'action', width: 200, align: 'center' },
]

// 表单数据
const dataList = ref<API.Space[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
	current: 1,
	pageSize: 10,
	sortField: 'createTime',
	sortOrder: 'descend',
	spaceLevel: undefined,
	userId: undefined,
})

// 分页参数
const pagination = computed(() => {
	return {
		current: searchParams.current ?? 1,
		pageSize: searchParams.pageSize ?? 10,
		total: total.value,
		showSizeChanger: true,
		showTotal: (total: number) => `总共 ${total} 条`,
	}
})

// 表格变化之后，重新获取数据
const doTableChange = (page: { current: number; pageSize: number }) => {
	searchParams.current = page.current
	searchParams.pageSize = page.pageSize
	fetchData()
}

// 获取数据
const fetchData = async () => {
	loading.value = true
	try {
		const res = await listSpaceByPageUsingPost({
			...searchParams,
		})
		if (res.data.code === 0 && res.data.data) {
			dataList.value = res.data.data.records ?? []
			total.value = res.data.data.total || 0
		} else {
			message.error('获取数据失败：' + res.data.message)
		}
	} catch {
		message.error('网络错误，请稍后再试')
	} finally {
		loading.value = false
	}
}

// 搜索操作
const doSearch = () => {
	// 重置当前页为1
	searchParams.current = 1
	// 重新获取数据
	fetchData()
}

// 重置搜索条件
const resetSearch = () => {
	// 重置搜索参数
	Object.assign(searchParams, {
		spaceLevel: undefined,
		userId: undefined,
		current: 1,
		pageSize: 10,
		sortField: 'createTime',
		sortOrder: 'descend',
	})
	// 重新获取数据
	fetchData()
}

// 删除操作
const doDelete = async (id: number) => {
	if (!id) {
		return
	}

	Modal.confirm({
		title: '⚠️ 危险操作确认',
		icon: createVNode(ExclamationCircleOutlined),
		content: `确定要删除这个空间吗？此操作不可恢复，请谨慎操作！\n\n空间ID: ${id}`,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 400,
		async onOk() {
			try {
				const res = await deleteSpaceUsingPost({ id })
				if (res.data.code === 0) {
					message.success('删除成功')
					// 删除成功后重新获取数据
					await fetchData()
				} else {
					message.error('删除失败：' + res.data.message)
				}
			} catch {
				message.error('删除失败，请重试')
			}
		},
	})
}

// 页面加载时获取数据，请求一次
onMounted(() => {
	// 初始化搜索参数
	fetchData()
})
</script>

<style scoped lang="scss"></style>
